package com.retoc.workflowable.controller;

import com.retoc.workflowable.common.R;
import com.retoc.workflowable.pojo.approve.ApproveReq;
import com.retoc.workflowable.pojo.approve.CheckInstanceReq;
import com.retoc.workflowable.pojo.approve.DeleteReq;
import org.flowable.engine.*;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/approve")
public class ApproveController {

    @Autowired
    ProcessEngine processEngine;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    HistoryService historyService;

    //删除请假申请
    @DeleteMapping("/DeleteProcessById")
    public HashMap<String, Object> DeleteProcessById(@Valid @RequestBody DeleteReq req){
        Task task = taskService.createTaskQuery().processInstanceId(req.getInstanceId()).singleResult();
        if (task==null){
            return R.error("实例ID错误！");
        }
        runtimeService.deleteProcessInstance(req.getInstanceId(),req.getReason());
//        System.out.println(req.getInstanceId()+"删除成功，原因为："+req.getReason());
        return R.ok();
    }

    //审批请假申请
    @PostMapping("/approval")
    public R approvalLeave(@Valid @RequestBody ApproveReq req) {
        Task task = taskService.createTaskQuery().processInstanceId(req.getInstanceId()).singleResult();
        //实例ID查不到则返回错误信息
        if (task==null){
            return R.error("实例ID错误！");
        }
        //如果同意审批，则完成审批任务跳到下一个步骤
        if ("Approved".equals(req.getApproval())){
            taskService.complete(task.getId());
            return R.ok().put("instanceId",task.getProcessInstanceId());
        }else {
            //如果不同意审批则删除任务并返回消息
            runtimeService.deleteProcessInstance(req.getInstanceId(),req.getReason());
            return R.ok().put("result","reject");
        }
    }

    //查询用户待审批工作流
    @PostMapping("/searchRequest")
    public R searchLeaveRequest(@Valid @RequestBody CheckInstanceReq req) {
        List<Task> list = taskService.createTaskQuery().taskAssignee(req.getCheckerId()).list();
        if (list.isEmpty()){
            return R.error("用户没有待审批工作");
        }
        List<HashMap<String,Object>> result=new ArrayList<>();
        list.forEach(task -> {
            HashMap<String,Object> map=new HashMap<>();
            Object type1 = taskService.getVariable(task.getId(), "types");
            map.put("step", task.getName());
//            Object type = runtimeService.getVariable(task.getExecutionId(), "type");
            map.put("instanceId",task.getProcessInstanceId());
            map.put("types",type1);
            result.add(map);
        });
        return R.ok().put("result",result);
    }
}
